{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 特殊方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Python** 使用 `__` 开头的名字来定义特殊的方法和属性，它们有：\n",
    "\n",
    "- `__init__()`\n",
    "- `__repr__()`\n",
    "- `__str__()`\n",
    "- `__call__()`\n",
    "- `__iter__()`\n",
    "- `__add__()`\n",
    "- `__sub__()`\n",
    "- `__mul__()`\n",
    "- `__rmul__()`\n",
    "- `__class__`\n",
    "- `__name__`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 构造方法 `__init__()`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "之前说到，在产生对象之后，我们可以向对象中添加属性。事实上，还可以通过构造方法，在构造对象的时候直接添加属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Leaf(object):\n",
    "    \"\"\"\n",
    "    A leaf falling in the woods.\n",
    "    \"\"\"\n",
    "    def __init__(self, color='green'):\n",
    "        self.color = color"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认属性值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "green\n"
     ]
    }
   ],
   "source": [
    "leaf1 = Leaf()\n",
    "\n",
    "print leaf1.color"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "传入有参数的值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "orange\n"
     ]
    }
   ],
   "source": [
    "leaf2 = Leaf('orange')\n",
    "\n",
    "print leaf2.color"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "回到森林的例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "class Forest(object):\n",
    "    \"\"\" Forest can grow trees which eventually die.\"\"\"\n",
    "    def __init__(self):\n",
    "        self.trees = np.zeros((150,150), dtype=bool)\n",
    "        self.fires = np.zeros((150,150), dtype=bool)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在构造方法中定义了两个属性 `trees` 和 `fires`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       ..., \n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False]], dtype=bool)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forest = Forest()\n",
    "\n",
    "forest.trees"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       ..., \n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False]], dtype=bool)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forest.fires"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "修改属性的值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ True, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       ..., \n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False]], dtype=bool)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forest.trees[0,0]=True\n",
    "forest.trees"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "改变它的属性值不会影响其他对象的属性值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       ..., \n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False],\n",
       "       [False, False, False, ..., False, False, False]], dtype=bool)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forest2 = Forest()\n",
    "\n",
    "forest2.trees"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "事实上，`__new__()` 才是真正产生新对象的方法，`__init__()` 只是对对象进行了初始化，所以：\n",
    "\n",
    "```python\n",
    "leaf = Leaf()\n",
    "```\n",
    "\n",
    "相当于\n",
    "\n",
    "```python\n",
    "my_new_leaf = Leaf.__new__(Leaf)\n",
    "Leaf.__init__(my_new_leaf)\n",
    "leaf = my_new_leaf\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 表示方法 `__repr__()` 和 `__str__()`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Leaf(object):\n",
    "    \"\"\"\n",
    "    A leaf falling in the woods.\n",
    "    \"\"\"\n",
    "    def __init__(self, color='green'):\n",
    "        self.color = color\n",
    "    def __str__(self):\n",
    "        \"This is the string that is printed.\"\n",
    "        return \"A {} leaf\".format(self.color)\n",
    "    def __repr__(self):\n",
    "        \"This string recreates the object.\"\n",
    "        return \"{}(color='{}')\".format(self.__class__.__name__, self.color)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`__str__()` 是使用 `print` 函数显示的结果："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A green leaf\n"
     ]
    }
   ],
   "source": [
    "leaf = Leaf()\n",
    "\n",
    "print leaf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`__repr__()` 返回的是不使用 `print` 方法的结果："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Leaf(color='green')"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "leaf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "回到森林的例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "class Forest(object):\n",
    "    \"\"\" Forest can grow trees which eventually die.\"\"\"\n",
    "    def __init__(self, size=(150,150)):\n",
    "        self.size = size\n",
    "        self.trees = np.zeros(self.size, dtype=bool)\n",
    "        self.fires = np.zeros((self.size), dtype=bool)\n",
    "        \n",
    "    def __repr__(self):\n",
    "        my_repr = \"{}(size={})\".format(self.__class__.__name__, self.size)\n",
    "        return my_repr\n",
    "    \n",
    "    def __str__(self):\n",
    "        return self.__class__.__name__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "forest = Forest()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`__str__()` 方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Forest\n"
     ]
    }
   ],
   "source": [
    "print forest"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`__repr__()` 方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Forest(size=(150, 150))"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forest"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`__name__` 和 `__class__` 为特殊的属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "__main__.Forest"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forest.__class__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Forest'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forest.__class__.__name__"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
